# coding=utf-8
import datetime
import random
import uuid

from django.conf import settings
from wechatpy.pay import WeChatPay
from wechatpy import client


def generate_order_serial_num():
    """
    生成订单流水号
    """
    part_1 = datetime.date.today().strftime("%Y%m%d")
    seed = uuid.uuid1().hex
    random.seed(seed)
    part_2 = str(random.randint(10000000, 99999999))
    return part_1 + part_2


def generate_invite_token():
    """
    生成抄写邀请码
    """
    return uuid.uuid1().hex


def upload_file(file):
    """
    上传文件，返回文件URL
    """
    # TODO
    return "http://www.baidu.com"


def init_wechat_pay():
    """
    初始化微信支付

    返回：
        微信支付对象
    """
    wechat_pay = WeChatPay(
        settings.APPID, settings.APPKEY, settings.MCHID,
        mch_cert=settings.WECHAT_PAY_CERT_DIR)
    return wechat_pay


def init_wechat_user_api():
    """
    初始化微信用户API
    """
    wechat_client = client.WeChatClient(
        settings.APPID, settings.APPSECRET)
    return wechat_client.user


def get_wx_user_infos(open_ids):
    user_api = init_wechat_user_api()
    res_infos = user_api.get_batch(set(open_ids))
    user_infos = {}
    for info in res_infos:
        open_id = info["openid"]
        user_infos[open_id] = info
    return user_infos
